<?php

namespace App\Http\Controllers;

use App\Exports\ClueExport;
use App\Http\Requests\ClueIndexRequest;
use App\Http\Requests\ClueSetTagRequest;
use App\Http\Resources\ClueIndexResource;
use App\Models\Clue;
use App\User;
use Illuminate\Http\Request;

class ClueController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param ClueIndexRequest $request
     * @return \Illuminate\Http\Resources\Json\ResourceCollection
     */
    public function index(ClueIndexRequest $request)
    {
        $type     = $request->get('type', 'zx');
        $pageSize = $request->get('page_size', 25);

        $start = $request->get('start_time');
        $end   = $request->get('end_time');

        $query = Clue::query()->with(['distributions', 'tags']);
        $query->whereDate('create_time', '>=', $start);
        $query->whereDate('create_time', '<=', $end);
        $this->orderBy($query, 'create_time');
        if ($type !== 'my') {
            $query->where('type', $type);
        } else {
            $user = $this->getUser();
            $query->whereHas('distributions', function ($q) use ($user) {
                $q->where('user_id', $user->id);
            });
        }

        $data = $query->paginate($pageSize);
        return ClueIndexResource::collection($data);
    }

    public function setTag(Clue $clue, ClueSetTagRequest $request)
    {
        $id = $request->get('id');

        $clue->tags()->sync($id);
        return $this->responseSuccess();
    }

    public function userClue(User $user, Request $request)
    {
        $pageSize = $request->get('page_size', 25);
        $query    = $user->clues();
        $this->orderBy($query, 'create_time');

        $data = $query->paginate($pageSize);
        return ClueIndexResource::collection($data);
    }

    public function exportExcel(ClueIndexRequest $request)
    {
        $type  = $request->get('type');
        $start = $request->get('start_time');
        $end   = $request->get('end_time');

        return (new ClueExport($type, $start, $end))->download('clues.xlsx');
    }
}
